from flask import Blueprint, request, jsonify, session, current_app, render_template
from datetime import datetime
import os
import uuid
from app.extensions import db
from werkzeug.utils import secure_filename

from app.models.user import CoupleRelationship, Album, Photo
from app.routes.api import login_required, login_required_html

photo_bp = Blueprint('photo_bp', __name__)

# 允许的文件类型
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def get_relationship(user_id):
    """获取用户的情侣关系（不强制要求存在）"""
    return CoupleRelationship.query.filter(
        ((CoupleRelationship.user1_id == user_id) |
         (CoupleRelationship.user2_id == user_id)) &
        (CoupleRelationship.status == 'accepted')
    ).first()


# 相册相关API
@photo_bp.route('/api/albums', methods=['GET'])
@login_required
def get_albums():
    """获取当前用户的所有相册（自己创建的+伴侣共享的，无情侣关系时仅自己的）"""
    user_id = session['user_id']

    # 获取情侣关系（可能为None）
    relationship = get_relationship(user_id)

    # 构建查询条件：自己创建的相册，若有情侣关系则增加共享相册
    query_conditions = [Album.creator_id == user_id]
    if relationship:
        query_conditions.append(Album.relationship_id == relationship.id)

    # 查询相册
    albums = Album.query.filter(
        db.or_(*query_conditions)
    ).order_by(Album.created_at.desc()).all()

    # 构建响应数据
    album_list = []
    for album in albums:
        cover_image_url = None
        if album.cover_photo_id:
            cover_photo = Photo.query.get(album.cover_photo_id)
            if cover_photo:
                cover_image_url = cover_photo.get_url()

        album_list.append({
            'id': album.id,
            'name': album.name,
            'description': album.description,
            'created_at': album.created_at.isoformat(),
            'photo_count': len(album.photos),
            'is_shared': album.is_shared,
            'cover_image_url': cover_image_url,
            'creator': {
                'id': album.creator.id,
                'nickname': album.creator.nickname
            }
        })

    return jsonify(album_list)


@photo_bp.route('/api/albums', methods=['POST'])
@login_required
def create_album():
    """创建新相册（无情侣关系时创建个人相册）"""
    user_id = session['user_id']
    data = request.json

    # 验证必填字段
    if not data.get('name'):
        return jsonify({'status': 'error', 'message': '相册名称不能为空'}), 400

    # 获取情侣关系（可能为None）
    relationship = get_relationship(user_id)

    # 创建相册（无情侣关系时relationship_id为None）
    new_album = Album(
        name=data.get('name'),
        description=data.get('description', ''),
        is_shared=data.get('is_shared', True) if relationship else False,  # 无情侣关系时默认不共享
        creator_id=user_id,
        relationship_id=relationship.id if relationship else None
    )

    db.session.add(new_album)
    db.session.commit()

    # 创建相册目录
    try:
        user_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], str(user_id))
        os.makedirs(user_dir, exist_ok=True)
        album_dir = os.path.join(user_dir, str(new_album.id))
        os.makedirs(album_dir, exist_ok=True)
    except Exception as e:
        current_app.logger.error(f"创建相册目录失败: {str(e)}")
        db.session.rollback()
        return jsonify({'status': 'error', 'message': '创建相册目录失败'}), 500

    return jsonify({
        'status': 'success',
        'message': '相册创建成功',
        'album': {
            'id': new_album.id,
            'name': new_album.name,
            'description': new_album.description
        }
    })


@photo_bp.route('/api/albums/<int:album_id>', methods=['GET'])
@login_required
def get_album(album_id):
    """获取指定相册的详细信息（仅自己创建或共享的）"""
    user_id = session['user_id']

    # 获取相册
    album = Album.query.get(album_id)
    if not album:
        return jsonify({'status': 'error', 'message': '相册不存在'}), 404

    # 获取情侣关系（可能为None）
    relationship = get_relationship(user_id)

    # 验证权限：自己创建的 或 有情侣关系且是共享相册
    is_own_album = album.creator_id == user_id
    is_shared_album = relationship and album.relationship_id == relationship.id
    if not (is_own_album or is_shared_album):
        return jsonify({'status': 'error', 'message': '没有权限查看此相册'}), 403

    # 处理封面
    cover_image_url = None
    if album.cover_photo_id:
        cover_photo = Photo.query.get(album.cover_photo_id)
        if cover_photo:
            cover_image_url = cover_photo.get_url()

    return jsonify({
        'id': album.id,
        'name': album.name,
        'description': album.description,
        'created_at': album.created_at.isoformat(),
        'photo_count': len(album.photos),
        'is_shared': album.is_shared,
        'cover_photo_id': album.cover_photo_id,
        'cover_image_url': cover_image_url,
        'creator': {
            'id': album.creator.id,
            'nickname': album.creator.nickname
        }
    })


@photo_bp.route('/api/albums/<int:album_id>', methods=['PUT'])
@login_required
def update_album(album_id):
    """更新相册信息（仅自己创建的）"""
    user_id = session['user_id']
    data = request.json

    # 获取相册
    album = Album.query.get(album_id)
    if not album:
        return jsonify({'status': 'error', 'message': '相册不存在'}), 404

    # 验证权限（只能修改自己创建的）
    # if album.creator_id != user_id:
    #   return jsonify({'status': 'error', 'message': '没有权限修改此相册'}), 403

    # 更新字段（无情侣关系时强制不共享）
    if 'name' in data:
        album.name = data['name']
    if 'description' in data:
        album.description = data['description']
    if 'is_shared' in data:
        relationship = get_relationship(user_id)
        album.is_shared = data['is_shared'] if relationship else False  # 无情侣关系时强制不共享

    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '相册更新成功'
    })


@photo_bp.route('/api/albums/<int:album_id>', methods=['DELETE'])
@login_required
def delete_album(album_id):
    """删除相册（仅自己创建的）"""
    user_id = session['user_id']

    # 获取相册
    album = Album.query.get(album_id)
    if not album:
        return jsonify({'status': 'error', 'message': '相册不存在'}), 404

    # 验证权限
    if album.creator_id != user_id:
        return jsonify({'status': 'error', 'message': '没有权限删除此相册'}), 403

    # 先删除相册目录
    album.delete_directory()

    # 删除相册记录
    db.session.delete(album)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '相册已删除'
    })


# 照片相关API
@photo_bp.route('/api/albums/<int:album_id>/photos', methods=['GET'])
@login_required
def get_album_photos(album_id):
    """获取指定相册的所有照片（验证权限）"""
    user_id = session['user_id']
    category = request.args.get('category','')
    sort_by = request.args.get('sort_by','')
    # 获取相册
    album = Album.query.get(album_id)
    if not album:
        return jsonify({'status': 'error', 'message': '相册不存在'}), 404

    # 获取情侣关系
    relationship = get_relationship(user_id)

    # 验证权限
    is_own_album = album.creator_id == user_id
    is_shared_album = relationship and album.relationship_id == relationship.id
    if not (is_own_album or is_shared_album):
        return jsonify({'status': 'error', 'message': '没有权限查看此相册'}), 403
    #  获取照片，构建查询并应用筛选排序
    query = Photo.query.filter_by(album_id=album_id)
    #应用照片可见性过滤：自己上传的或标记为共享的
    query = query.filter(
        (Photo.uploaded_by  == user_id) | (Photo.is_shared == True)
    )
    # 筛选分类
    if category:
        query = query.filter(Photo.category == category)
    # 排序处理
    if sort_by == 'newest':
        query = query.order_by(Photo.created_at.desc())
    elif sort_by == 'oldest':
        query = query.order_by(Photo.created_at.asc())
    elif sort_by == 'date_taken':
        query = query.order_by(Photo.date_taken.desc())
    # 默认按拍摄日期降序
    else:
        query = query.order_by(Photo.date_taken.desc())
    photos = query.all()

    return jsonify([{
        'id': photo.id,
        'title': photo.title,
        'description': photo.description,
        'image_url': photo.get_url(),
        'date_taken': photo.date_taken.isoformat() if photo.date_taken else None,
        'category': photo.category,
        'created_at': photo.created_at.isoformat(),
        'is_shared': photo.is_shared,
        'uploaded_by': {
            'id': photo.uploader.id,
            'nickname': photo.uploader.nickname
        }
    } for photo in photos])


@photo_bp.route('/api/photos', methods=['POST'])
@login_required
def upload_photo():
    """上传照片（允许上传到自己的相册，无论是否有情侣关系）"""
    user_id = session['user_id']

    # 检查文件
    if 'file' not in request.files:
        return jsonify({'status': 'error', 'message': '没有上传文件'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'status': 'error', 'message': '请选择文件'}), 400

    if file and allowed_file(file.filename):
        # 获取表单数据
        album_id = request.form.get('album_id')
        if not album_id:
            return jsonify({'status': 'error', 'message': '请选择相册'}), 400

        # 验证相册
        album = Album.query.get(album_id)
        if not album:
            return jsonify({'status': 'error', 'message': '相册不存在'}), 404

        # 验证权限：自己的相册 或 有情侣关系的共享相册
        relationship = get_relationship(user_id)
        is_own_album = album.creator_id == user_id
        is_shared_album = relationship and album.relationship_id == relationship.id
        if not (is_own_album or is_shared_album):
            return jsonify({'status': 'error', 'message': '没有权限上传到该相册'}), 403

        # 保存文件
        filename_ext = secure_filename(file.filename).rsplit('.', 1)[1].lower()
        filename = f"{uuid.uuid4()}.{filename_ext}"

        # 确保目录存在
        user_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], str(user_id))
        album_dir = os.path.join(user_dir, str(album_id))
        os.makedirs(album_dir, exist_ok=True)

        # 保存文件
        file_path = os.path.join(album_dir, filename)
        try:
            file.save(file_path)
        except Exception as e:
            current_app.logger.error(f"保存照片失败: {str(e)}")
            return jsonify({'status': 'error', 'message': '保存照片失败'}), 500

        # 创建照片记录
        title = request.form.get('title', '') or f"照片_{datetime.now().strftime('%Y%m%d%H%M%S')}"
        date_taken = request.form.get('date_taken')
        new_photo = Photo(
            title=title,
            description=request.form.get('description', ''),
            filename=filename,
            date_taken=datetime.strptime(date_taken, '%Y-%m-%d').date() if date_taken else None,
            category=request.form.get('category', ''),
            is_shared=request.form.get('is_shared', 'true').lower() == 'true' if relationship else False,
            album_id=album_id,
            uploaded_by=user_id
        )

        db.session.add(new_photo)
        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': '照片上传成功',
            'photo': {
                'id': new_photo.id,
                'title': new_photo.title,
                'image_url': new_photo.get_url()
            }
        })

    return jsonify({'status': 'error', 'message': '不支持的文件类型'}), 400


@photo_bp.route('/api/photos/<int:photo_id>', methods=['GET'])
@login_required
def get_photo(photo_id):
    """获取照片详情（验证权限）"""
    user_id = session['user_id']

    # 获取照片
    photo = Photo.query.get(photo_id)
    if not photo:
        return jsonify({'status': 'error', 'message': '照片不存在'}), 404

    # 验证权限
    album = Album.query.get(photo.album_id)
    relationship = get_relationship(user_id)
    
    is_own_photo = photo.uploaded_by == user_id
    is_own_album = album.creator_id == user_id
    is_shared_album = relationship and album.relationship_id == relationship.id
    
    if not (is_own_photo or is_own_album or is_shared_album):
        return jsonify({'status': 'error', 'message': '没有权限查看此照片'}), 403

    return jsonify({
        'id': photo.id,
        'title': photo.title,
        'description': photo.description,
        'image_url': photo.get_url(),
        'date_taken': photo.date_taken.isoformat() if photo.date_taken else None,
        'category': photo.category,
        'created_at': photo.created_at.isoformat(),
        'is_shared': photo.is_shared,
        'album': {
            'id': album.id,
            'name': album.name
        },
        'uploaded_by': {
            'id': photo.uploader.id,
            'nickname': photo.uploader.nickname
        }
    })


@photo_bp.route('/api/photos/<int:photo_id>', methods=['PUT'])
@login_required
def update_photo(photo_id):
    """更新照片信息（仅自己上传的）"""
    user_id = session['user_id']
    data = request.json

    # 获取照片
    photo = Photo.query.get(photo_id)
    if not photo:
        return jsonify({'status': 'error', 'message': '照片不存在'}), 404

    # 验证权限
    # if photo.uploaded_by != user_id:
    #     return jsonify({'status': 'error', 'message': '没有权限修改此照片'}), 403

    # 更新字段（无情侣关系时强制不共享）
    if 'title' in data:
        photo.title = data['title']
    if 'description' in data:
        photo.description = data['description']
    if 'date_taken' in data:
        photo.date_taken = datetime.strptime(data['date_taken'], '%Y-%m-%d').date() if data['date_taken'] else None
    if 'category' in data:
        photo.category = data['category']
    if 'is_shared' in data:
        relationship = get_relationship(user_id)
        photo.is_shared = data['is_shared'] if relationship else False  # 无情侣关系时强制不共享

    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '照片信息更新成功'
    })


@photo_bp.route('/api/photos/<int:photo_id>', methods=['DELETE'])
@login_required
def delete_photo(photo_id):
    """删除照片（仅自己上传的）"""
    user_id = session['user_id']

    # 获取照片
    photo = Photo.query.get(photo_id)
    if not photo:
        return jsonify({'status': 'error', 'message': '照片不存在'}), 404

    # 验证权限
    if photo.uploaded_by != user_id:
        return jsonify({'status': 'error', 'message': '没有权限删除此照片'}), 403

    # 删除文件和记录
    photo.delete_file()
    db.session.delete(photo)
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '照片已删除'
    })


@photo_bp.route('/api/photos/shared', methods=['GET'])
@login_required
def get_shared_photos():
    """获取共享的照片列表（无情侣关系时返回空）"""
    user_id = session['user_id']

    # 获取查询参数
    category = request.args.get('category', '')
    sort_by = request.args.get('sort_by', 'newest')

    # 获取情侣关系（无关系时返回空列表）
    relationship = get_relationship(user_id)
    if not relationship:
        return jsonify([])  # 无情侣关系时返回空列表

    # 构建查询
    query = Photo.query.join(
        Album,
        onclause=Photo.album_id == Album.id
    ).filter(
        (Album.relationship_id == relationship.id) &
        (Photo.uploaded_by != user_id)
    )
    #应用照片可见性过滤：自己上传的或标记为共享的
    query = query.filter(
        (Photo.uploaded_by  == user_id) | (Photo.is_shared == True)
    )
    # 应用筛选和排序
    if category:
        query = query.filter(Photo.category == category)
    if sort_by == 'newest':
        query = query.order_by(Photo.created_at.desc())
    elif sort_by == 'oldest':
        query = query.order_by(Photo.created_at.asc())
    elif sort_by == 'date_taken':
        query = query.order_by(Photo.date_taken.desc())

    photos = query.all()

    # 格式化响应
    return jsonify([{
        'id': photo.id,
        'title': photo.title,
        'description': photo.description,
        'image_url': photo.get_url(),
        'date_taken': photo.date_taken.isoformat() if photo.date_taken else None,
        'category': photo.category,
        'created_at': photo.created_at.isoformat(),
        'is_shared': photo.is_shared,
        'album': {
            'id': photo.album.id,
            'name': photo.album.name
        },
        'uploaded_by': {
            'id': photo.uploader.id,
            'nickname': photo.uploader.nickname
        }
    } for photo in photos])


@photo_bp.route('/api/photos', methods=['GET'])
@login_required
def get_photos():
    """获取符合条件的照片（自己的+共享的，无情侣关系时仅自己的）"""
    user_id = session['user_id']

    # 获取查询参数
    category = request.args.get('category', '')
    sort_by = request.args.get('sort_by', 'newest')

    # 获取情侣关系
    relationship = get_relationship(user_id)

    # 构建查询条件：自己的照片，若有情侣关系则增加共享照片
    query_conditions = [Photo.uploaded_by == user_id]
    if relationship:
        query_conditions.append(
            db.and_(
                Album.relationship_id == relationship.id,
                Photo.album_id == Album.id
            )
        )

    # 构建查询
    query = Photo.query.join(
        Album,
        onclause=Photo.album_id == Album.id
    ).filter(
        db.or_(*query_conditions)
    )
    #应用照片可见性过滤：自己上传的或标记为共享的
    query = query.filter(
        (Photo.uploaded_by  == user_id) | (Photo.is_shared == True)
    )
    # 应用筛选和排序
    if category:
        query = query.filter(Photo.category == category)
    if sort_by == 'newest':
        query = query.order_by(Photo.created_at.desc())
    elif sort_by == 'oldest':
        query = query.order_by(Photo.created_at.asc())
    elif sort_by == 'date_taken':
        query = query.order_by(Photo.date_taken.desc())

    photos = query.all()

    # 格式化响应
    return jsonify([{
        'id': photo.id,
        'title': photo.title,
        'description': photo.description,
        'image_url': photo.get_url(),
        'date_taken': photo.date_taken.isoformat() if photo.date_taken else None,
        'category': photo.category,
        'created_at': photo.created_at.isoformat(),
        'is_shared': photo.is_shared,
        'album': {
            'id': photo.album.id,
            'name': photo.album.name
        },
        'uploaded_by': {
            'id': photo.uploader.id,
            'nickname': photo.uploader.nickname
        }
    } for photo in photos])


@photo_bp.route('/api/albums/<int:album_id>/cover', methods=['PUT'])
@login_required
def set_album_cover(album_id):
    """设置相册封面（仅自己创建的）"""
    user_id = session['user_id']
    data = request.json

    if not data or 'cover_photo_id' not in data:
        return jsonify({'status': 'error', 'message': '请指定封面照片ID'}), 400

    # 获取相册
    album = Album.query.get(album_id)
    if not album:
        return jsonify({'status': 'error', 'message': '相册不存在'}), 404

    # 验证权限
    # if album.creator_id != user_id:
    #    return jsonify({'status': 'error', 'message': '没有权限设置该相册封面'}), 403

    # 验证照片
    photo = Photo.query.filter_by(id=data['cover_photo_id'], album_id=album_id).first()
    if not photo:
        return jsonify({'status': 'error', 'message': '照片不存在或不属于该相册'}), 404

    # 更新封面
    album.cover_photo_id = data['cover_photo_id']
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '相册封面设置成功',
        'cover_photo_id': album.cover_photo_id
    })


@photo_bp.route('/photos')
@login_required_html
def moments_page():
    """渲染照片页面"""
    return render_template('photos.html')